package com.core.image.tcp;

import com.core.image.core.box.StringRecevicePacket;
import com.core.image.handler.ConnectorStringPacketChain;

import java.util.ArrayList;
import java.util.List;

/**
 * describe:
 *
 * @author 库琦
 * @date 2020/02/05/23:32
 */
public class Group {
    private final String name;
    private final GroupMessageAdapter adapter;
    private final List<ConnectorHandler> members = new ArrayList<>();
    Group(String name,GroupMessageAdapter adapter){
        this.name = name;
        this.adapter = adapter;
    }
    String getName(){
        return name;
    }
    boolean addMember(ConnectorHandler handler){
        synchronized (members){
            if (!members.contains(handler)){
                handler.getStringPacketChain()
                        .appendLast(new ForwardConnectorStringPacketChain());
                System.out.println("Group[" + name + "] add new member:" );
                return true;
            }
        }
        return false;
    }
    /**
     * 移除某个客户端
     *
     * @param handler 客户端
     * @return 是否移除成功
     */
    boolean removeMember(ConnectorHandler handler) {
        synchronized (members) {
            if (members.remove(handler)) {
                handler.getStringPacketChain()
                        .remove(ForwardConnectorStringPacketChain.class);
                System.out.println("Group[" + name + "] leave member:" );
                return true;
            }
        }
        return false;
    }
    private class ForwardConnectorStringPacketChain extends ConnectorStringPacketChain{

        @Override
        public boolean consume(ConnectorHandler clientHandler, StringRecevicePacket packet) {
            synchronized (members){
                for (ConnectorHandler member:members){
                    if (member == clientHandler){
                        continue;
                    }
                    adapter.sendMessageToClient(clientHandler,packet.entity());
                }
                return true;
            }

        }
    }

    interface GroupMessageAdapter {
        /**
         * 发送消息的接口
         *
         * @param handler 客户端
         * @param msg     消息
         */
        void sendMessageToClient(ConnectorHandler handler, String msg);
    }
}
